layui.use(["zlContext", "zltreemenu"], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , layer = layui.layer
        , table = layui.table
        , form = layui.form
        , zltreemenu = layui.zltreemenu
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , dataName = zlConfig.global.result.dataName
        , OK = zlConfig.global.result.okState
        , fullheight = 'full-30'
        , loadingLayer
        , baseUrl = layui.cache['contentPath'] + '/manager/coremodelshow/?modelId=';

    var options = {
        float: false,
        auto: true,
        always_show_resize_handle: true,
    };
    var frmTemplate = [
        '<div>'
        , '  <div class="grid-stack-item-content">'
        , '     <div class="grid-stack-item-header"><h5 class="item-title">标题</h5>'
        , '         <div class="grid-stack-item-operate">'
        , '             <button class="layui-btn layui-btn-primary layui-btn-sm edit-btn"><i class="layui-icon layui-icon-edit"></i></button>'
        , '             <button class="layui-btn layui-btn-primary layui-btn-sm del-btn"><i class="layui-icon layui-icon-delete"></i></button>'
        , '         </div>'
        , '     </div>'
        , '     <div class="grid-stack-item-body"></div>'
        , '  </div>'
        , '</div>'
    ];
    var defaultNode = {
        x: 0,
        y: 0,
        width: 4,
        height: 8
    }

    //渲染
    $('.grid-stack').gridstack(options);

    var gridstackAction = new function () {
        var that = this;
        this.items = [];
        this.grid = $('.grid-stack').data('gridstack');

        //增加
        this.addNewWidget = function () {
            var node = this.items.pop() || {
                x: 0,
                y: 0,
                width: 4,
                height: 8
            };
            this.grid.addWidget($(frmTemplate.join("")),
                node.x, node.y, node.width, node.height);
            return false;
        }.bind(this);

        //清空
        this.clearGrid = function () {
            zlContext.confirm('询问', '是否要清空设计好的大屏?', function (index) {
                gridstackAction.grid.removeAll();
                layer.close(index)
                return false;
            });
        }.bind(this);
        // 获取页面数据
        this.getData= function (){
            var selector = '.grid-stack > .' + (options.itemClass ? options.itemClass : 'grid-stack-item') + ':visible';
            var curdata;
            curdata= _.map($(selector), function (el) {
                var $el = $(el);
                var node = $el.data('_gridstack_node');
                var data = {}; 
                if (typeof node.id != 'undefined') {
                    data['id'] = node.id;
                }
                if (typeof node.x != 'undefined') {
                    data['x'] = node.x;
                }
                if (typeof node.y != 'undefined') { 
                    data['y'] = node.y; 
                }
                if (typeof node.width != 'undefined') {
                    data['width'] = node.width;
                }
                if (typeof node.height != 'undefined') { 
                    data['height'] = node.height;
                }
                if (typeof node.minWidth != 'undefined') {
                    data['minWidth'] = node.minWidth;
                }
                if (typeof node.maxWidth != 'undefined') {
                    data['maxWidth'] = node.maxWidth;
                }
                if (typeof node.minHeight != 'undefined') {
                    data['minHeight'] = node.minHeight;
                }
                if (typeof node.maxHeight != 'undefined') {
                    data['maxHeight'] = node.maxHeight; 
                }
                if (typeof node.locked != 'undefined') { 
                    data['locked'] = node.locked; 
                }
                if (typeof node.noMove != 'undefined') { 
                    data['noMove'] = node.noMove; 
                }
                if (typeof node.noResize != 'undefined') { 
                    data['noResize'] = node.noResize; 
                }
                if(typeof node.autoPosition != 'undefined'){
                    data['autoPosition'] = node.autoPosition;
                }
                data['zlRwid'] = $el.find('.grid-stack-item-content').attr('data-zl-rwid');
                data['titleName'] = $el.find('.grid-stack-item-content .grid-stack-item-header .item-title').text();
                data['theme'] = $("#largescreen-theme").val();
                return data;
            }, this);  
            return curdata;        
        }.bind(this);

        //保存
        this.saveGrid = function () {     
            var content = this.getData();
            var params = {
                "RWID": $('.layui-hide input[name=RWID]').val(),
                "LS_CONTENT": JSON.stringify(content),
            }
            loadingLayer = layer.msg('数据保存中，请稍候...', { icon: 16, time: false, shade: 0.1 });
            zlContext.post(layui.cache['contentPath'] + '/manager/largescreen/content/modify', params, function (result) {
                if (result[statusName] = OK) {
                    zlContext.successMsg('保存成功');
                } else {
                    zlContext.errorMsg(result[msgName]);
                }
                layer.close(loadingLayer);
            });

        }.bind(this);

        $('#add-new-widget').click(this.addNewWidget);

        $('.design-header #btn-clear').click(this.clearGrid);

        $('.design-header #btn-save').click(this.saveGrid);

        $('.design-header #btn-preview').click(function () {
            var content = gridstackAction.getData();        
            var url = layui.cache['contentPath'] + '/manager/largescreen/preview?tokenId=' + getTokenId();
            var tempForm = document.createElement("form");      
            var OBJNAME = $('input[name=OBJNAME]').val(); 
            tempForm.id="tempForm1";         
            tempForm.method="post";        
            tempForm.action=url;    
            tempForm.target="大屏展示";         
            tempForm.innerHTML="<input type='hidden' name='LS_CONTENT' value='"+JSON.stringify(content)+"'/><input type='hidden' name='OBJNAME' value='"+OBJNAME+"'/>";
            tempForm.addEventListener("onsubmit",function(){ window.open('about:blank',"大屏展示"); });   //chrome    
            document.body.appendChild(tempForm);             
            tempForm.dispatchEvent(new Event("onsubmit"));//chrome    
            //必须手动的触发，否则只能看到页面刷新而没有打开新窗口  
            tempForm.submit();
            document.body.removeChild(tempForm);
        });

        $(".grid-stack").on('click', ".grid-stack-item-content .grid-stack-item-operate .del-btn", function () {
            var $delItem = $(this).parents('.grid-stack-item');
            gridstackAction.grid.removeWidget($delItem);
        });

        $(".grid-stack").on('click', ".grid-stack-item-content .grid-stack-item-operate .edit-btn", function () {
            var $editItem = $(this).parents('.grid-stack-item');
            gridAction.editTitleGrid($editItem);
        });

        // 添加主题背景设置
        $('#bigScreentheme').click(function(){
            layer.open({
                type: 1
                , title: "配置主题"
                , area: ["500px", "250px"]
                , content: $("#configTheme")
                , btn: ['确定', '取消']
                , success: function () {
                    form.render();
                }
                , yes: function (index, layero) {
                    form.on('submit(config-theme-form-btn)', function(data){
                        var themeVal = data.field.themeConfig;
                        // componentRender.bigScreenTheme(themeVal);
                        $("#largescreen-theme").val(themeVal);
                        var url="";
                        if(themeVal!=""){
                            var cssObj = themeVal;
                            url = layui.cache['contentPath'] + '/static/libs/formdesign/css/bigscreenTheme/'+cssObj+'.css';
                        }
                        $('#theme-css').attr("href",url);
                        layer.close(index)
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                    $("#config-theme-form-btn").trigger("click");
            
                }
            })
        })
    }

    var gridAction = {
        curEditItem: undefined,
        fromDesignTree: undefined,
        editTitleGrid: function ($item) {
            var setting = gridAction.fromDesignTree.setting;
            setting.check.chkStyle = 'radio';
            setting.check.radioType = 'all';
            gridAction.fromDesignTree.setting = setting;
            gridAction.fromDesignTree.refresh();

            var rwid = $item.find('.grid-stack-item-content').attr('data-zl-rwid');
            if(rwid){
                var node = gridAction.fromDesignTree.getNodeByParam('RWID', rwid, null);
                if(node){
                    //选择当前节点
                    gridAction.fromDesignTree.checkNode(node, true, true);
                }
            }
            gridAction.curEditItem = $item;
            gridAction.formTreeGrid('edit');
        },
        formTreeGrid: function (type) {
            loadingLayer = layer.msg('数据加载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
            layer.open({
                type: 1
                , id: 'formDesignTreeLayer'
                , title: "选择大屏模块"
                , area: ["800px", "680px"]
                , content: $('#formTreeContainer')
                , btn: ['确定', '取消']
                , success: function () {
                    layer.close(loadingLayer);
                }
                , yes: function (index, layero) {
                    var nodes = gridAction.fromDesignTree.getCheckedNodes(true);
                    if('edit' == type){
                        //编辑
                        if(nodes && nodes.length > 0 && gridAction.curEditItem){
                            var node = nodes[0];
                            var newRwid = node['RWID'];
                            var oldRwid = gridAction.curEditItem.find('.grid-stack-item-content').attr('data-zl-rwid');
                            if(newRwid != oldRwid){
                                gridAction.curEditItem.find('.grid-stack-item-content').attr('data-zl-rwid',newRwid);
                                gridAction.curEditItem.find('.grid-stack-item-header .item-title').text(node['OBJNAME']);
                                gridAction.curEditItem.find('.grid-stack-item-body iframe').attr('src',baseUrl + newRwid);
                            }
                        }
                    }else{
                        //添加
                        if (nodes) {
                            if (nodes.length > 10) {
                                zlContext.warnMsg("选择的个数不能大于10");
                                return false;
                            }
                            $.each(nodes, function(i, node){
                                var rwid = node['RWID'];
                                var titleName = node['OBJNAME'];
                                var url = baseUrl + rwid;
    
                                var $item = $(frmTemplate.join(''));
                                $item.find('.grid-stack-item-content').attr('data-zl-rwid', rwid);
                                $item.find('.grid-stack-item-content').css('height', '100%');
                                $item.find('.grid-stack-item-header .item-title').text(titleName);
                                $item.find('.grid-stack-item-body').css("height","calc(100% - 41px)");
                                $item.find('.grid-stack-item-body').append('<iframe src="' + url + '" width=100% height=100%></iframe>');
                                var mod = i % 3;
                                gridstackAction.grid.addWidget($item, defaultNode.x + defaultNode.width * mod , defaultNode.y, defaultNode.width, defaultNode.height);
                                
                            });
                        }
                    }
                    gridAction.fromDesignTree.checkAllNodes(false);
                    //收缩
                    gridAction.fromDesignTree.expandAll(false);
                    layer.close(index);
                }
                , btn2: function (index, layero) {
                    gridAction.fromDesignTree.checkAllNodes(false);
                    //收缩
                    gridAction.fromDesignTree.expandAll(false);
                }
                , cancel: function (index, layero) {
                    gridAction.fromDesignTree.checkAllNodes(false);
                    //收缩
                    gridAction.fromDesignTree.expandAll(false);
                }
            });
        },
        initFromTree: function () {
            gridAction.fromDesignTree = zltreemenu.render('formDesignTree', {
                checkEnable: true,
                autoCheckTrigger: true,
                chkboxType: { "Y": "ps", "N": "s" },
                radioType: "all",
                dataurl: layui.cache['contentPath'] + "/manager/coremodeldesign/query",
                type: "post",
                idKey: "RWID",
                search: false,
                dataFilter: function (treeId, parentNode, responseData) {
                    if (responseData[statusName] == OK) {
                        var data = responseData[dataName];
                        return data;
                    }
                    else {
                        zlContext.errorMsg(responseData[msgName]);
                    }
                    return responseData;
                }
            }, {});
        }
    }

    var largeScreenRender = {
        content: undefined,
        queryContentById: function(rwid){
            var url = layui.cache['contentPath'] + '/manager/largescreen/querybyid';
            var params = {
                'RWID': rwid
            }
            zlContext.asyncGet(url, params, function(result){
                if(result[statusName] == OK){
                    var obj = result[dataName];
                    if(obj){
                        if(obj['LS_CONTENT']){
                            largeScreenRender.content = JSON.parse(obj['LS_CONTENT']);
                        }
                        $('.layui-hide input[name="OBJNAME"]').val(obj['OBJNAME']);
                    }
                }else{
                    zlContext.errorMsg(result[msgName]);
                }
            }, false);
        },
        render: function(){
            //内容不存在
            if(!largeScreenRender.content || largeScreenRender.content.length <= 0){
                return;
            }
            var lsContent = largeScreenRender.content;
            var url="";
            var cssObj = "";
            if(lsContent[0].hasOwnProperty('theme')){
                cssObj =lsContent[0].theme;
                url = layui.cache['contentPath'] + '/static/libs/formdesign/css/bigscreenTheme/'+cssObj+'.css';
            }
            $('#theme-css').attr("href",url);
            $("#largescreen-theme").val(cssObj)
            $.each(largeScreenRender.content, function(index, node){
                var rwid = node['zlRwid'];
                var titleName = node['titleName'] || '标题';
                var $item = $(frmTemplate.join(''));
                if (typeof node.locked != 'undefined') { 
                    $item.attr('data-gs-locked', node.locked); 
                }
                if (typeof node.noMove != 'undefined') { 
                    $item.attr('data-gs-no-move', node.noMove); 
                }
                if (typeof node.noResize != 'undefined') {
                    $item.attr('data-gs-no-resize', node.noResize); 
                }
                var url = baseUrl + rwid;
                $item.find('.grid-stack-item-content').attr('data-zl-rwid', rwid);
                $item.find('.grid-stack-item-header .item-title').text(titleName);
                $item.find('.grid-stack-item-body').css("height","calc(100% - 41px)");
                $item.find('.grid-stack-item-body').append('<iframe src="' + url + '" width=100% height=100%></iframe>');
                gridstackAction.grid.addWidget($item, node['x'], node['y'], node['width'],node['height'], 
                    node['autoPosition'], node['minWidth'], node['maxWidth'], node['minHeight'], node['maxHeight'], node['id']);

            });
        }
    }

    loadingLayer = layer.msg('数据加载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
    //初始化资源树
    gridAction.initFromTree();
    //查询大屏展示的内容
    largeScreenRender.queryContentById($('.layui-hide input[name="RWID"]').val());
    //渲染大屏
    largeScreenRender.render();
    layer.close(loadingLayer);
    //展示资源树
    $('.design-header #btn-add').click(function () {
        var setting = gridAction.fromDesignTree.setting;
        setting.check.chkStyle = 'checkbox';
        setting.check.radioType = 'level';
        gridAction.fromDesignTree.setting = setting;
        gridAction.fromDesignTree.refresh();
        gridAction.fromDesignTree.checkAllNodes(false);
        gridAction.formTreeGrid('add');
    });

    // $(".grid-stack").css({ "height": $(window).height() - 63, "min-height": $(window).height() - 140 });
    // z自适应控制页面高度
    $(window).resize(function () {
        var height = $(window).height() - 63;
        // $("body").css("min-height", $(window).height() - 90);
        // $(".grid-stack").css({ "height": height, "min-height": $(window).height() - 140 });
        // $(".sidebar-nav").css({ "height": $(window).height(), "min-height": $(window).height() - 65 })
    });
});